import React from 'react'
import {get} from '../../../fetch/get.js'
import ListComponent from '../../../components/List'
import LoadMore from '../../../components/LoadMore'

class List extends React.Component{
    constructor(props){
        super(props)
        this.state={
            data: [], // 存储列表数据
            hasMore: false, // 记录当前状态是否还有更多数据
            isLoadingMore: false,  //记录当前状态是否正在加载中，true为正在加载中
            page: 1  // 记录下一页的页码，首页为0
        }
    }
    render() {
        return (
            <div>
                {this.state.data.length? <ListComponent title="猜你喜欢" data={this.state.data}></ListComponent> : <div>加载中2222</div>}
                {
                    this.state.hasMore
                    ? <LoadMore isLoadingMore = {this.state.isLoadingMore}  loadMoreFn = {this.loadMoreData.bind(this)}/>
                    : <div>已经是最后一页</div>
                }
            </div>
        )
    }
    componentDidMount() {
        this.loadFirstPageData()
    }

    loadFirstPageData() {  //获取首屏数据
        const cityName = this.props.cityName
        const page = 0
        const result = get('/api/homelist/' + cityName +'/' + page)
        this.resultHandle(result)
    }

    loadMoreData() { //加载更多数据
        //记录状态
        this.setState(
            {
                isLoadingMore: true
            }
        )
        const cityName = this.props.cityName
        const page = this.state.page
        const result = get('/api/homelist/' + cityName +'/' + page)
        this.resultHandle(result)

        this.setState({
            page: page + 1,
            isLoadingMore: false
        })
    }

    resultHandle(result) {
        result.then((res) => {
            return res.json()
        }).then((json) => {
            const hasMore = json.hasMore
            const data = json.data
            this.setState({
                hasMore: hasMore,
                data: this.state.data.concat(data)
            })
        })
    }
}

export default List